//
//  WXComposeView.swift
//  weibo
//
//  Created by 王旭 on 16/4/25.
//  Copyright © 2016年 王旭. All rights reserved.

//自定义菜单按钮界面

import UIKit
import pop

class WXComposeView: UIView {
    
    private var menuButtons : [WXComposeButton] = []
    
    //当前视图添加到的控制器
    private var targetVC : UIViewController?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
//给外界提供的添加方法
    func show(targetVC:UIViewController?) {
      targetVC?.view.addSubview(self)
        //关联属性
        self.targetVC = targetVC
    }
    
    override func didMoveToSuperview() {
        super.didMoveToSuperview()
        //执行按钮动画

        
        //遍历保存的自定义菜单按钮
        for (index,value) in menuButtons.enumerate() {
            
            menuBurronAnimation(value, index: index, isUp: true)
            
//            //1.初始化动画对象
//            let anim = POPSpringAnimation(propertyNamed: kPOPViewCenter)
//            //2.设置结束位置
//            anim.toValue = NSValue(CGPoint: CGPoint(x: value.center.x, y: value.center.y - 350))
//            //3.设置动画属性
//              //弹性
//            anim.springBounciness = 8
//              //速度
//            anim.springSpeed = 10
//--------------------以下为测试代码-----------------
//            //延迟执行
//            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(Double(index ) * 0.025 * Double(NSEC_PER_SEC))),dispatch_get_main_queue()) { () -> Void in
//                //4.添加动画
//                value.pop_addAnimation(anim, forKey: nil)
//            }
//--------------------以上为测试代码-----------------
            //4.添加动画
            //设置动画开始时间
//            anim.beginTime = Double(index) * 1 + CACurrentMediaTime()
//            print(CACurrentMediaTime())
//            value.pop_addAnimation(anim, forKey: nil)
            
            
        }
    }
    
//触摸事件->取消按钮的动画
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        super.touchesBegan(touches, withEvent: event)
        
        //按钮消失动画
        for (index,value) in menuButtons.reverse().enumerate() {
            menuBurronAnimation(value, index: index, isUp: false)
        }
        
        //延迟执行
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(0.5 * Double(NSEC_PER_SEC))),dispatch_get_main_queue()) { () -> Void in
            //移除当前view
            self.removeFromSuperview()
        }

    }
    
//自定义按钮动画方法
    private func menuBurronAnimation(value:UIView,index:Int,isUp:Bool) {
        //1.初始化动画对象
        let anim = POPSpringAnimation(propertyNamed: kPOPViewCenter)
        //2.设置结束位置
        anim.toValue = NSValue(CGPoint: CGPoint(x: value.center.x, y: value.center.y + (isUp ? -350 : 350)))
        //3.设置动画属性
        //弹性
        anim.springBounciness = 8
        //速度
        anim.springSpeed = 10
        //4.添加动画
        //设置动画开始时间
        anim.beginTime = Double(index) * 0.025 + CACurrentMediaTime()
        value.pop_addAnimation(anim, forKey: nil)
    }
    
//布局界面
    func setupUI() {
        //设置frame
//        frame = UIScreen.mainScreen().bounds
        
        //获取图片
        let image = printScrren()
        
        //添加磨砂背景
        let effectImage = image.applyLightEffect()
        let effectImageView = UIImageView(image: effectImage)
        addSubview(effectImageView)
        
        //添加中间的图片框
        addSubview(centerImageView)
        
        //设置约束
        centerImageView.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(self)
            make.top.equalTo(self).offset(100)
        }
        
        //添加自定义菜单按钮
        addMenuButton()
        
//        //设置背景色
//        backgroundColor = UIColor.redColor()
        
//        //把图片转成二进制
//        let data = UIImagePNGRepresentation(image)
//        //保存到桌面
//        data?.writeToFile("/Users/wx/Desktop/halo", atomically: true)
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        //在此设置frmae闪一下就消失
        frame = UIScreen.mainScreen().bounds
    }
    

    
//提供自定义按钮数据的方法
    private func provideButtonArray()->[WXComposeButtonModel] {
        //获取路径
        let path = NSBundle.mainBundle().pathForResource("compose.plist", ofType: nil)
        //读取文件
        let array = NSArray(contentsOfFile: path!)
        
        //字典转模型
          //定义可变数组
        var tempArr : [WXComposeButtonModel] = []
        for value in array! {
            let model = WXComposeButtonModel(dic: value as! [String:AnyObject])
            tempArr.append(model)
        }
        return tempArr
    }
    
//添加自定义菜单按钮的方法
    private func addMenuButton() {
        
        //获取按钮的间距
        let composeButtonW : CGFloat = 80
        let composeButtonH : CGFloat = 110
        let numOfRowButtons :CGFloat = 3
        let composeMargin :CGFloat = (SCREEN_W - numOfRowButtons * composeButtonW) / (2 + numOfRowButtons - 1)
//        print(composeMargin)
        //获得自定义按钮数据
        let array = provideButtonArray()
        
        for (i,value) in array.enumerate() {
            
            //实例化
            let button = WXComposeButton(titleColor: UIColor.blackColor(), fontSize: 14)
            //设置点击事件
            button.addTarget(self, action: "menuButtonClick:", forControlEvents: UIControlEvents.TouchUpInside)
            //设置tag
            button.tag = i
            //设置Size
            button.frame.size = CGSize(width: composeButtonW, height: composeButtonH)
              //获得按钮的行列
            let row = i / Int(numOfRowButtons)
            let col = i % Int(numOfRowButtons)
//            print("\(row)--\(col)")
            button.frame.origin.x = CGFloat(col+1) * composeMargin + CGFloat(col) * composeButtonW
            button.frame.origin.y = CGFloat(row) * composeMargin + CGFloat(row) * composeButtonH + SCRREN_H
//            print("\(button.frame.origin.x)--\(button.frame.origin.y)")
            //设置文本
            button.setTitle(value.title, forState: UIControlState.Normal)
            //设置图片
            button.setImage(UIImage(named: value.icon!), forState: .Normal)
            //添加到父view上
            addSubview(button)
            menuButtons.append(button)
        }
    }
    
//自定义菜单按钮点击事件
   @objc private func menuButtonClick(button:UIButton) {
        UIView.animateWithDuration(0.25, animations: { () -> Void in
            for value in self.menuButtons{
                value.alpha = 0.01
                if value == button {
                    value.transform = CGAffineTransformMakeScale(2, 2)
                }else{
                    value.transform = CGAffineTransformMakeScale(0.5, 0.5)
                }
            }
            }) { (_) -> Void in
//                UIView.animateWithDuration(0.25, animations: { () -> Void in
//                    for value in self.menuButtons {
//                        value.alpha = 1
//                        value.transform = CGAffineTransformIdentity
//                    }
//                })
                    
//--------------------以下为测试代码:通过现有类直接实例化目标控制器-----------------
//                    let vc : WXComposeViewController = WXComposeViewController()
//--------------------以上为测试代码:通过现有类直接实例化目标控制器-----------------
                
                //从plist文件中实例化目标控制器
                //获得菜单按钮的数组
                let array = self.provideButtonArray()
                //获取模型
                let model = array[button.tag]
                let className = NSClassFromString(model.className!) as! UIViewController.Type
                let vc = className.init()
//--------------------以下为测试代码-----------------
//                print(NSStringFromClass(WXComposeViewController.self))
//                
//                let className = NSClassFromString("weibo.WXComposeViewController")
//                print(className)
//--------------------以上为测试代码-----------------
                    self.targetVC?.presentViewController(UINavigationController(rootViewController: vc), animated: true, completion: { () -> Void in
                        //从父父view移除当前
                        self.removeFromSuperview()
                })
        }
    }
    
//截取当前屏幕方法
    private func printScrren()->UIImage {
        //获得主屏幕   强行解包,屏幕一定存在
        let window = UIApplication.sharedApplication().keyWindow!
        //获得图形区域
        let rect = window.frame
        //1.开启图形上下文
        UIGraphicsBeginImageContextWithOptions(rect.size, false, UIScreen.mainScreen().scale)
//        //使用此种方式获得是屏幕大小图
//        UIGraphicsBeginImageContext(rect.size)
        //2.把屏幕内容渲染到上下文
        window.drawViewHierarchyInRect(rect, afterScreenUpdates: true)
        //3.从图形上下文取得图片
        let image = UIGraphicsGetImageFromCurrentImageContext()
        //4.关闭图形上下文
        UIGraphicsEndImageContext()
        //5.保存图片(返回图片)
        return image
    }
    
//懒加载控件
    private lazy var centerImageView :UIImageView = UIImageView(image: UIImage(named: "compose_slogan"))
    

}
